package vn.cent.games.findnumber.main;

import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import vn.cent.games.findnumber.beans.GameBean;
import vn.cent.games.findnumber.beans.PlayerBean;
import vn.cent.games.findnumber.utils.Commands;

import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;

/**
 * UserDisconnectedEventHandler: manager disconnected user events
 * 
 * @author TV.Vinh
 * @version 1.0
 */
public class UserDisconnectedEventHandler extends BaseServerEventHandler {

	/**
	 * Handle user disconnected event
	 * 
	 * @param event
	 *            The received event
	 */
	@Override
	public void handleServerEvent(ISFSEvent evt) throws SFSException {

		// get current active games
		ConcurrentHashMap<Integer, GameBean> active_games = ((FindNumberExtension) getParentExtension())
				.getGames();

		// Get user that leaved
		User user = (User) evt.getParameter(SFSEventParam.USER);
		
		// Get room that user left
		Room room = null;
		@SuppressWarnings("unchecked")
		List<Room> joinedRooms = (List<Room>) evt
				.getParameter(SFSEventParam.JOINED_ROOMS);
		if (joinedRooms.size() > 0) {
			room = joinedRooms.get(0);
//			trace("user: " + user.getName() + " left room: " + room.getName());
		} else {
			return;
		}
		
		GameBean lastJoinedGame = active_games.get(room.getId());
		if (lastJoinedGame != null) {

			// TODO find winner (remain player), WARNING: NULL DATA
			User winner = FindWinner(lastJoinedGame, user);
//			ISFSObject resObj = new SFSObject();

			// notify the user still in game is winner
			if (winner != null) {
				((FindNumberExtension) getParentExtension()).send(
						Commands.CMD_BOT, null, winner);

//				trace("hey, have fun with BOT: " + winner.getName());
			}
			// TODO end game
			active_games.remove(lastJoinedGame.getRoom().getId(),
					lastJoinedGame);
			// lastJoinedGame = null;
		}

	}

	private User FindWinner(GameBean game, User leaveUser) {

		for (Entry<Integer, PlayerBean> iterable_element : game.getPlayers()
				.entrySet()) {
			PlayerBean player = iterable_element.getValue();
			if (player.getId() != leaveUser.getId()) {
				return player.getSfsUser();
			}
		}

		return null;
	}

}
